package storages

import (
	"github.com/pkg/errors"
	"gluenet/internal/glue-srvm/model"
	"gorm.io/gorm"
)

type accountToHostStorage struct{}

var DefaultAccountToHostStorage = &accountToHostStorage{}

func (c *accountToHostStorage) Insert(db *gorm.DB, data model.MeteringAccountToHost) (uint, error) {
	return uint(data.Id), errors.WithStack(db.Create(&data).Error)
}

func (c *accountToHostStorage) Update(db *gorm.DB, filter, data model.MeteringAccountToHost) error {
	return errors.WithStack(db.Model(data).Where(&filter).Updates(&data).Error)
}

func (c *accountToHostStorage) DeleteByID(db *gorm.DB, id uint) error {
	if id == 0 {
		return errors.New("ID cannot be empty.")
	}
	return errors.WithStack(db.Delete(&model.MeteringAccountToHost{Id: uint64(id)}).Error)
}

func (c *accountToHostStorage) FindOne(db *gorm.DB, filter model.MeteringAccountToHost) (*model.MeteringAccountToHost, error) {
	var accountToHost model.MeteringAccountToHost
	err := db.Where(&filter).Find(&accountToHost).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, nil
	}
	return &accountToHost, errors.WithStack(err)
}

func (c *accountToHostStorage) FindAll(db *gorm.DB, filter model.MeteringAccountToHost) ([]model.MeteringAccountToHost, error) {
	var accountToHosts []model.MeteringAccountToHost
	err := db.Where(&filter).Find(&accountToHosts).Error
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, errors.WithStack(err)
	}
	return accountToHosts, nil
}
